package com.incito.crawl.common.httpclient;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 检测过期和空闲的HttpConnection，并关掉它们
 * Created by wuyu on 14-7-1.
 */
public class IdleConnectionMonitor extends Thread {
    private static Logger logger = LoggerFactory.getLogger(IdleConnectionMonitor.class);
    private final PoolingHttpClientConnectionManager poolingConnMgr;
    private volatile boolean shutdown;
    private String monitorName;
    private long interval = 5000; //缺省5秒轮询关闭一次超时和失效的连接

    public IdleConnectionMonitor(PoolingHttpClientConnectionManager poolingConnMgr,long interval) {
        this("default",poolingConnMgr,interval);
    }

    public IdleConnectionMonitor(String monitorName,PoolingHttpClientConnectionManager poolingConnMgr,long interval) {
        super();
        this.setDaemon(true);
        this.monitorName = monitorName;
        this.poolingConnMgr = poolingConnMgr;
        if (interval > 5000) {
            this.interval = interval;
        }
    }

    @Override
    public void run() {
        try {
            logger.info("..............IdleConnectionMonitor started,[Name:{},Interval:{}]..............",monitorName,interval);
            while (!shutdown) {
                synchronized (this) {
                    wait(interval);

                    // Close expired connections
                    poolingConnMgr.closeExpiredConnections();
                    // Optionally, close connections
                    // that have been idle longer than 30 sec
                    poolingConnMgr.closeIdleConnections(30, TimeUnit.SECONDS);

                    logger.debug("poolingConnMgr close expired and idle connections [Name:{},Interval:{}] ......",monitorName,interval);
                }
            }
        } catch (InterruptedException ex) {
            logger.info("..............IdleConnectionMonitor terminated,[Name:{},Interval:{}]..............",monitorName,interval);
        }
    }

    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }

}
